# -*- coding: utf-8 -*-
import os
import sys
import json
import getpass
import hashlib
from pprint import pprint
from prettytable import PrettyTable

sys.path.append(os.path.realpath("."))
import inquirer  # noqa
import time as t


def readFile(path):
    with open(path,"r",encoding="utf8") as f:
        stu_data = json.load(f)
    return stu_data

stu_data = readFile("./data/stuData.json")

def Preservation():
    with open("./data/stuData.json","w",encoding="utf8") as f:
        json.dump(stu_data,f)

def men_main():
    print('='*40)
    print('\033[31m\t 学生管理系统V10.0\033[0m')
    t.sleep(0.5)
    questions = [
          inquirer.List(
              "option",
               message="\033[33m请选择",
                   choices=["添加学生信息", "删除学生信息", "修改学生信息","搜索学生信息","查询所有学生信息", "退出系统"],
        ),
    ]

    answers = inquirer.prompt(questions)

    return answers['option']

name_stu = lambda : input("[\033[33m?\033[0m] 请输入学生姓名：")
sex = lambda : input("[\033[33m?\033[0m] 请输入学生性别：")
age = lambda : int(input("[\033[33m?\033[0m] 请输入学生年龄："))
love = lambda : input("[\033[33m?\033[0m] 请输入学生爱好：")
stu_id = lambda : input("[\033[33m?\033[0m] 请输入学生学号：")
OptionInfo = lambda val: print(f"\033[32m{val}\033[0m")
OptionFialInfo = lambda val: print(f"\033[31m{val}\033[0m")
WatchUserInput = lambda val: input(f'[\033[33m?\033[0m] {val}')
WatchUserPasswd = lambda val: getpass.getpass(f"[\033[33m?\033[0m] {val}")
findStudentById = lambda stu_id: [i for i in stu_data if i['stu_id'] == stu_id]
findStudentByName = lambda name_stu: [i for i in stu_data if name_stu in i["name"]]
def AddStudent():
    res = {}
    student_id = stu_id()
    if len(student_id) == 9:
        res['stu_id'] = student_id
    else:
        print('\033[31m学号输入有误\033[0m')
        student_id = stu_id()
        res['stu_id'] = student_id
    for i in stu_data:
        if i['stu_id'] == student_id:
            return -1
            break
    res['name'] = name_stu()
    res['sex'] = sex()
    res['age'] = age()
    res['love'] = love()
    return res

def DeleteStudent(stu_id):
    getStudentObj = findStudentById(stu_id)
    if len(getStudentObj) != 0:
        stu_data.remove(getStudentObj[0])
        return -1


def SearchAll(stu_data):
    table = PrettyTable()
    table.field_names = ["姓名", "学号", "性别", "年龄", "爱好"]
    for i in stu_data:
        table.add_row([i['name'],i['stu_id'],i['sex'],i['age'],i['love']])

    print(table)
def UpdataStudent(stu_id):
    getStudentObj = findStudentById(stu_id)
    if len(getStudentObj) == 0:
        OptionFialInfo("此学号无效,查无此人！！！")
    else:
        questions = [
                      inquirer.Checkbox('optionUpdata',
                          message="你要修改以下哪些信息?",
                          choices=['姓名', '性别', '学号', '年龄', '爱好'],),
                     ]
        answers = inquirer.prompt(questions)
        for i in answers['optionUpdata']:
            if i == '姓名':
                getStudentObj[0]['name'] = name_stu()
                continue
            elif i == '性别':
                getStudentObj[0]['sex'] = sex()
                continue
            elif i == '学号':
                getStudentObj[0]['stu_id'] = stu_id()
                continue
            elif i == '年龄':
                getStudentObj[0]['age'] = age()
                continue
            else:
                getStudentObj[0]['love'] = love()
                continue

def md5Passwd(val):
    m = hashlib.md5()
    b = val.encode(encoding="utf8")
    m.update(b)
    md5 = m.hexdigest()
    return md5

def login():
    user =  WatchUserInput("请输入用户名：")
    passwd = WatchUserPasswd("请输入你的密码: ")
    loginData = readFile("./etc/users.json")
    if user == loginData["username"]:
        if md5Passwd(passwd) == loginData["password"]:
            return True
        else:
            if md5Passwd(WatchUserPasswd("请重新输入你的密码: ")) == loginData["password"]:
                return True
            else:
                return False
    else:
        OptionFialInfo("此用户尚未注册！")
        return False
           

def main():
    t.sleep(0.5)
    while True:
        res = men_main()
        if res == "添加学生信息": 
            res = AddStudent()
            if res == -1:
                OptionFialInfo("添加失败，此学号已被注册！！！")
            else:
                OptionInfo("please waiting...")
                t.sleep(0.5)
                stu_data.append(res)
        elif res == "查询所有学生信息": 
            OptionInfo("loading...")
            t.sleep(0.5)
            SearchAll(stu_data)
        elif res == "搜索学生信息":
            val = WatchUserInput("请输入要搜索的学生姓名：")
            OptionInfo("loading...")
            t.sleep(0.5)
            res = findStudentByName(val)
            if len(res) == 0:
                OptionFialInfo("无结果")
            else:
                SearchAll(res)
        elif res == "删除学生信息":
            val = WatchUserInput("请输入要删除的学生学号：")
            OptionInfo("deleting...")
            t.sleep(0.5)
            blog = DeleteStudent(val)
            OptionFialInfo(f"删除失败,{val}不存在！！！") if blog != -1 else print()
        elif res == "修改学生信息":
            val = WatchUserInput("请输入要修改的学生学号：")
            OptionInfo("updating...")
            t.sleep(0.5)
            UpdataStudent(val)
        elif res == "退出系统":
            OptionInfo("preservationing...")
            t.sleep(0.5)
            Preservation()
            OptionInfo("bye ^__^ ~")
            break 


if __name__ == '__main__':
    if login():
        main()
    else:
        OptionFialInfo("登录失败！！！")
